package com.csw.service;

import com.csw.bean.Student;
import com.csw.dao.StudentDao;
import com.csw.util.RedisUtil;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

public class StudentService {

    private StudentDao studentDao = new StudentDao();

    public Student queryStudentById(String id) {

        /*
         * key : student_cache:id
         *
         */

        //1、查询缓存数据库中是否有需要查询的数据

        String key = "student_cache:" + id;

        Jedis jedis = null;
        try {
            jedis = RedisUtil.getConnection();
            Map<String, String> map = jedis.hgetAll(key);


            if (map != null && !map.isEmpty()) {

                Student student = new Student();
                student.setId(id);
                student.setName(map.get("name"));
                student.setAge(Integer.parseInt(map.get("age")));
                student.setGender(map.get("gender"));
                student.setClazz(map.get("clazz"));

                //更新过期时间
                jedis.expire(key, 10);

                //返回查询到的数据
                return student;
            }

        } catch (Exception e) {
            System.out.println("读取缓存失败");
        } finally {
            if (jedis != null) {
                //返回到连接池中
                jedis.close();
            }
        }

        //如果缓存中没有，再查询数据库
        Student student = studentDao.queryStudentById(id);

        if (student == null) {
            return null;
        }

        //将查询到的数据保存到缓存中

        try {
            jedis = RedisUtil.getConnection();
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("name", student.getName());
            hashMap.put("age", student.getAge().toString());
            hashMap.put("gender", student.getGender());
            hashMap.put("clazz", student.getClazz());

            jedis.hmset(key, hashMap);

            //增加过期时间
            jedis.expire(key, 10);


        } catch (Exception e) {
            System.out.println("写入缓存失败");
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }


        return student;
    }
}
